/*
 * @Author: 260156 260156@gree.com.cn
 * @Date: 2022-08-17 14:28:24
 * @LastEditors: 260156 260156@gree.com.cn
 * @LastEditTime: 2022-08-17 17:16:40
 * @FilePath: \gree-zst-web\src\utils\request\downloadFile.ts
 * @Description:
 *
 * Copyright (c) 2022 by 260156 260156@gree.com.cn, All Rights Reserved.
 */
import { ElMessage } from "element-plus";
import type { DownloadResult, DownloadRequestOptions } from "#/request";

type Params = DownloadRequestOptions & {
  data: DownloadResult;
};

/**
 * @description: 导出文件
 * @param {Params} param1：{data必传, fileName/ext选传（默认系统名称+日期.xlsx）}
 * @return {*}
 */
export function downloadFile({ data, fileName, ext }: Params) {
  const date = new Date().toJSON().substring(0, 10).replace(/-/g, "");
  fileName = (fileName || `${import.meta.env.VITE_APP_TITLE}`) + " " + date;
  ext = ext || "xlsx";
  const blob = new Blob([data]);
  // 非IE下载
  if ("download" in document.createElement("a")) {
    const elink = document.createElement("a");
    elink.download = `${fileName}.${ext}`;
    elink.style.display = "none";
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    URL.revokeObjectURL(elink.href);
    document.body.removeChild(elink);
  } else {
    // IE10+
    const error = "浏览器不支持导出";
    ElMessage.error(error);
    Error(error);
  }
}
